package com.atguigu.demo1;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

public class MyLen extends GenericUDF {
    @Override
    //自定义UDF函数
    public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
        //1.约束函数传入参数的个数
        if(arguments.length!=1){
            throw new UDFArgumentLengthException("args num is not one!!!");
        }
        //2.函数传入参数的类型:基本类型
        if(!arguments[0].getCategory().equals(ObjectInspector.Category.PRIMITIVE)){
            throw new UDFArgumentTypeException(0,"args type is not primitive");//第一个参数:第几个数据 第二个参数:错误信息
        }
        //3.函数返回值的类型,求长度Int就行
        return PrimitiveObjectInspectorFactory.javaIntObjectInspector;
    }

    @Override
    public Object evaluate(DeferredObject[] arguments) throws HiveException {
        //函数功能的实现
        int length = arguments[0].get().toString().length();
        return length;
    }
        //返回空串就可
    @Override
    public String getDisplayString(String[] children) {
        return "";
    }
}
